package com.agileai.crm.module.procustomer.handler;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import jxl.Cell;
import jxl.CellType;
import jxl.DateCell;
import jxl.Sheet;
import jxl.Workbook;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.agileai.common.KeyGenerator;
import com.agileai.crm.common.BaseExcelImportHandler;
import com.agileai.domain.DataParam;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.NullRenderer;
import com.agileai.hotweb.renders.RedirectRenderer;
import com.agileai.hotweb.renders.ViewRenderer;

/**
 * generated by miscdp
 */
public class ProcustUploadHandler extends BaseExcelImportHandler{
	public ProcustUploadHandler(){
		super();
	}
	
	public ViewRenderer prepareDisplay(DataParam param) {
		this.setAttributes(param);
		this.processPageAttributes(param);
		return new LocalRenderer(getPage());
	}
	
	protected void processPageAttributes(DataParam param){
		
	}
	
    @SuppressWarnings("rawtypes")
    @PageAction
    public ViewRenderer uploadFile(DataParam param) {
    	log.info("abc");
        try {
            DiskFileItemFactory fac = new DiskFileItemFactory();
            ServletFileUpload fileFileUpload = new ServletFileUpload(fac);
            fileFileUpload.setHeaderEncoding("utf-8");

            List fileList = null;
            fileList = fileFileUpload.parseRequest(request);

            Iterator it = fileList.iterator();
            String name = "";
            String fileFullPath = null;
            File filePath = this.buildResourseSavePath(resourceGroupId);

            while (it.hasNext()) {
                FileItem item = (FileItem) it.next();

                if (item.isFormField()) {
                    String fieldName = item.getFieldName();

                    if (fieldName.equals("BIZ_ID")) {
                        String bizId = item.getString();
                        resourceParam.put("BIZ_ID", bizId);
                    }

                    continue;
                }

                name = item.getName();
                resourceParam.put("GRP_ID", resourceGroupId);
                resourceParam.put("RES_NAME", name);

                String location = resourceRelativePath + "/" + name;
                resourceParam.put("RES_LOCATION", location);
                fileFullPath = filePath.getAbsolutePath() + File.separator +
                               name;
                setAttribute("location",location);
                long resourceSize = item.getSize();
                resourceParam.put("RES_SIZE", String.valueOf(resourceSize));

                String suffix = name.substring(name.lastIndexOf("."));
                resourceParam.put("RES_SUFFIX", suffix);
                resourceParam.put("RES_SHAREABLE", "Y");
                
                //sort排序添加
//                String bizId = param.get("BIZ_ID");
//                List<DataRow> results = getResourceUploadService().findResourceRelations(bizId);
//                int resSort = results.size()+1;
//                resourceParam.put("RES_SORT", resSort);

                File tempFile = new File(fileFullPath);

                if (!tempFile.getParentFile().exists()) {
                    tempFile.getParentFile().mkdirs();
                }
                item.write(tempFile);
                
                String soId = request.getParameter("SO_ID");
                param.put("SO_ID", soId);
                
                String year = request.getParameter("RIR_YEAR");
                String period = request.getParameter("RIR_PERIOD");
                String rirPeriod = year + period;
                param.put("RIR_PERIOD", rirPeriod);
                
                String templateTypeId = request.getParameter("RIR_TEMPLATE_TYPE");
                String templateTypeName = "";
                if("gqtzhzb".equals(templateTypeId)){
                	templateTypeName = "股权投资项目汇总与重大项目明细表";
                }
                if("fgqcxtzhzb".equals(templateTypeId)){
                	templateTypeName = "非股权存续投资汇总表";
                }
                if("tzywzyzbdzb".equals(templateTypeId)){
                	templateTypeName = "投资业务主要指标对照表";
                }
                param.put("RIR_TEMPLATE_ID", templateTypeId);
                param.put("RIR_TEMPLATE", templateTypeName);
                
                param.put("RIR_SO_ID",soId);
                
//                this.insertResourceRecord();
//                getService().createtContentRecord("RiskImportReport", param);
                
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new NullRenderer();
    }
	
	@PageAction
	public ViewRenderer back(DataParam param){
		return new RedirectRenderer(getHandlerURL("MainWin"));
	}

	@Override
	protected void buildParams(File uploadedFile, List<DataParam> dataParams)
			throws Exception {
    	Workbook tempWorkbook = Workbook.getWorkbook(uploadedFile);
    	KeyGenerator keyGenerator = KeyGenerator.instance();
    	Sheet sheet = tempWorkbook.getSheet(0);
    	int rows = sheet.getRows();
    	int startIndex = 1;
    	for (int i = startIndex;i < rows;i++){
    		DataParam param = new DataParam();
    		param.put("RIR_ID",keyGenerator.genKey());
    		
    		Cell codeCell = sheet.getCell(0, i);
    		String codeValue = codeCell.getContents();
    		param.put("RSB_CODE",codeValue);
    		
    		if(!codeValue.equalsIgnoreCase("")){
	    		Cell nameCell = sheet.getCell(1, i);
	    		String nameValue = nameCell.getContents();
	    		param.put("RSB_NAME",nameValue);
	    		
	    		Cell socodeCell = sheet.getCell(2, i);
	    		String socodeCellValue = socodeCell.getContents();
	    		param.put("RSB_ORGANIZATION",socodeCellValue);
	
	    		DataParam querySoIdParam = new DataParam();
	    		querySoIdParam.put("SO_CODE", socodeCellValue);
	    		String soId = "12313";
	    		if(!soId.isEmpty()){
	    			param.put("SO_ID",soId);
	    		}
	    		
	    		Cell effectTimeCell = sheet.getCell(3, i);
	    		String cellcon = "";
	    		if(effectTimeCell.getType() == CellType.DATE){
	    			  DateCell dc = (DateCell)effectTimeCell;
	    			  Date date = dc.getDate();
	    			  SimpleDateFormat ds = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
	    			  cellcon = ds.format(date);
	    			}
	    		param.put("RSB_EFFECT_TIME",cellcon);
	    		
	    		Cell failureTimeCell = sheet.getCell(4, i);
	    		String cellconfail = "";
	    		if(failureTimeCell.getType() == CellType.DATE){
	    			  DateCell dc = (DateCell)failureTimeCell;
	    			  Date date = dc.getDate();
	    			  SimpleDateFormat ds = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
	    			  cellconfail = ds.format(date);
	    			}
	    		param.put("RSB_FAILURE_TIME",cellconfail);
	    		
	    		Cell rsbStateCell = sheet.getCell(5, i);
	    		String rsbStateValue = rsbStateCell.getContents();
	    		if(rsbStateValue.equalsIgnoreCase("未提交")){
	    			rsbStateValue = "INIT";
	    		}
	    		if(rsbStateValue.equalsIgnoreCase("已提交")){
	    			rsbStateValue = "SUBMIT";
	    		}
	    		if(rsbStateValue.equalsIgnoreCase("已上报")){
	    			rsbStateValue = "REPORTED";
	    		}
	    		if(rsbStateValue.equalsIgnoreCase("已作废")){
	    			rsbStateValue = "CANCELLED";
	    		}
	    		if(rsbStateValue.equalsIgnoreCase("已审核")){
	    			rsbStateValue = "AUDIT";
	    		}
	    		param.put("RSB_STATE",rsbStateValue);
	    		
	    		param.put("RSB_ORDER",1);
	    		
	    		User user = (User) getUser();		
	    		param.put("RSB_CREATE_ID",user.getUserId());
	    		
	    		param.put("RSB_CREATE_TIME",new Date());
	    		
	    		param.put("RSB_APPROVE_ID",null);
	    		
	    		param.put("RSB_APPROVE_TIME",null);
	    		
	    		dataParams.add(param);
    		}
    	}
    }

	@Override
	protected void importRecords(List<DataParam> dataParams) {
//    	RiskImportReportRecordManage RiskImportReportRecordManage = this.lookupService(RiskImportReportRecordManage.class);
    	log.info("dataParams is:"+dataParams);
//    	RiskImportReportRecordManage.importRecords(dataParams);
	}		
}
